package com.kk.clone.ShallowClone;

import cn.hutool.core.clone.CloneRuntimeException;
import cn.hutool.core.clone.Cloneable;

/**
 * 浅克隆,嵌套对象不会被克隆，克隆出来的嵌套对象地址不变
 * <p>
 * 1.实现Hutool提供的Cloneable接口，但要重写Object的clone方法。
 *
 * @author 王志强
 * @date 2022-02-21
 */
public class Cat implements Cloneable<Cat> {

    private final String name = "miaomiao";
    private int age = 200;
    private Cat catChild = null;

    public static void main(String[] args) throws InterruptedException {
        Cat cat = new Cat();
        cat.catChild = new Cat();
        cat.catChild.age = 100;

        // 实现克隆
        Cat cloneCat = cat.clone();

        System.out.println("原对象：");
        System.out.println(cat
                + " - " + cat.name
                + " - " + cat.age
                + " - " + cat.catChild.age);

        System.out.println("克隆对象：");
        System.out.println(cloneCat
                + " - " + cloneCat.name
                + " - " + cloneCat.age
                + " - " + cloneCat.catChild.age);

        // 现在改变原对象的catChild的属性，浅克隆的问题就暴露出来了，克隆对象的属性会跟着改变
        cat.catChild.age = 50;

        System.out.println("\n=============改变age属性后=============");
        System.out.println("原对象：");
        System.out.println(cat
                + " - " + cat.name
                + " - " + cat.age
                + " - " + cat.catChild.age);

        System.out.println("克隆对象：");
        System.out.println(cloneCat
                + " - " + cloneCat.name
                + " - " + cloneCat.age
                + " - " + cloneCat.catChild.age);

    }

    @Override
    public Cat clone() {
        try {
            return (Cat) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new CloneRuntimeException(e);
        }
    }


}

